import React from 'react';
import { Input, Form, DatePicker, Spin, Modal, notification } from 'antd';
import { get as getPath } from 'object-path';
import { utils } from 'vv-frontend-components';
import moment from 'moment';
import { SearchInput, SelectForm } from '@/components/UserForm';
import { getTypeList, getOverLong, getemployeelist } from '@/services/attendance/overtime';
import request from '@/utils/request';
import { formatSecond } from '@/utils/utils';

const { deepTrim } = utils;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
/**
 * 格式化Moment对象
 * @param {time} time
 * @param {string} format
 */
const formatTime = ({ time, format = 'YYYY-MM-DD HH:mm:00' }) => {
    const [startTime, endTime] = time;
    return {
        startTime: startTime.format(format),
        endTime: endTime.format(format)
    };
};

/**
 * 加班补录
 */
class BuluCollection extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            loading: false,
            departmentName: null
        };
    }

    /** 姓名选中的回调 */
    handleSelect = (e = '') => {
        console.log(e);
        const tmpArr = e.split('-');
        this.setState({ departmentName: getPath(tmpArr, 1, '') });
    };

    /**
     * 唤起弹窗方法
     */
    show = () => {
        const { form } = this.props;
        form.resetFields();
        this.setState({ visible: true, departmentName: null });
    };

    /**
     * 点击时间控件确定按钮
     */
    pickerOnOk = async v => {
        const {
            form: { setFieldsValue }
        } = this.props;
        this.setState({ loading: true });
        const result = await getOverLong(formatTime({ time: v }));
        this.setState({ loading: false });
        if (result && result.code === 10000) {
            setFieldsValue({ timeLong: formatSecond(result?.data?.data ?? 0) }); // 接口返回的是分钟
        } else {
            setFieldsValue({ timeLong: '' });
            notification.error({
                message: `请求错误 ${result.msg}`
            });
        }
    };

    /**
     * 添加加班记录
     */
    addOverTime = async D => {
        const url = '/api/oa/v1/overtime/add';
        const { time, name, timeLong, ...other } = D;
        const { startTime, endTime } = formatTime({ time });
        this.setState({ loading: true });
        const result = await request(url, {
            method: 'POST',
            data: deepTrim({
                ...other,
                employeeCode: name ? name.split('-')[0] : '',
                applyEndTime: endTime,
                applyStartTime: startTime
            })
        });
        this.setState({ loading: false });
        if (result && result.code === 10000) {
            notification.success({
                message: `${result.msg}`
            });
            return result.data;
        }
        notification.error({
            message: `请求错误 ${result.msg}`
        });
        return null;
    };

    saveUpdate = () => {
        const { form, callBack } = this.props;

        form.validateFields(async (err, value) => {
            if (!err) {
                await this.addOverTime(value);
                this.setState({ visible: false });
                callBack();
            }
        });
    };

    render() {
        const { visible, loading, departmentName } = this.state;
        const storeUser = localStorage.getItem('user');
        const user = storeUser ? JSON.parse(storeUser) : {};
        const {
            form: { getFieldDecorator }
        } = this.props;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            }
        };

        JSON.stringify({ m: moment() });

        return (
            <Modal
                title="加班手动补录"
                visible={visible}
                destroyOnClose
                onOk={this.saveUpdate}
                confirmLoading={loading}
                onCancel={() => this.setState({ visible: false })}
                centered
            >
                <Spin spinning={loading}>
                    <Form {...formItemLayout}>
                        <Form.Item label="姓名">
                            {getFieldDecorator('name', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择员工姓名'
                                    }
                                ]
                            })(
                                <SearchInput
                                    params={{
                                        organizationCode: user?.firstOrgInfo?.firstCompanyCode,
                                        queryCurrentCompanyEmployee: true
                                    }}
                                    getData={params =>
                                        getemployeelist(params).then(res => {
                                            if (res && res.code === 10000) {
                                                return res.data || [];
                                            }
                                            return [];
                                        })
                                    }
                                    selectProps={{
                                        placeholder: '请输入员工姓名',
                                        allowClear: true
                                    }}
                                    fieldsName={{
                                        value: 'employeeCode',
                                        title: 'employeeName',
                                        extraParams: 'name',
                                        isBuLu: true
                                    }}
                                    onChange={this.handleSelect}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="组织机构">
                            <Input value={departmentName} disabled />
                        </Form.Item>
                        <Form.Item label="加班类型">
                            {getFieldDecorator('overtimeSign', {
                                initialValue: null,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择加班类型'
                                    }
                                ]
                            })(
                                <SelectForm
                                    params={{ dictCode: 'overtimeSign' }}
                                    requireParam={['dictCode']}
                                    getData={params =>
                                        getTypeList(params).then(res => {
                                            if (res && res.code === 10000 && res.data) {
                                                return res.data || [];
                                            }
                                            return [];
                                        })
                                    }
                                    fieldsName={{
                                        selectValue: 'dictValue',
                                        selectTitle: 'dictName'
                                    }}
                                    selectProps={{
                                        placeholder: '请选择状态',
                                        style: { width: '100%' }
                                    }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="补录时间">
                            {getFieldDecorator('time', {
                                initialValue: '',
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择开始和结束时间'
                                    }
                                ]
                            })(
                                <RangePicker
                                    style={{ width: '100%' }}
                                    showTime={{ format: 'HH:mm' }}
                                    format="YYYY-MM-DD HH:mm"
                                    placeholder={['开始时间', '结束时间']}
                                    onOk={this.pickerOnOk}
                                    allowClear={false}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="时长">
                            {getFieldDecorator('timeLong', {
                                initialValue: '',
                                rules: [
                                    {
                                        required: true,
                                        message: '时长不能为空！'
                                    }
                                ]
                            })(<Input disabled />)}
                        </Form.Item>
                        <Form.Item label="补录事由" help="2-60个字符">
                            {getFieldDecorator('applicationNo', {
                                initialValue: '',
                                rules: [
                                    {
                                        required: true
                                    },
                                    {
                                        min: 2,
                                        max: 60
                                    }
                                ]
                            })(<TextArea placeholder="请输入补录原因" rows={4} />)}
                        </Form.Item>
                    </Form>
                </Spin>
            </Modal>
        );
    }
}
export default Form.create()(BuluCollection);
